//
// Created by kaifamiao on 2022/3/18.
//

#ifndef READ_CSV_RD_H
#define READ_CSV_RD_H

#endif //READ_CSV_RD_H
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <string.h>

using namespace std;



int  strstr_cnt( const   char   * string ,  const   char   * substring)  {
    int i,j,k,count = 0;
    for (i = 0; string[i]; i++){
        for (j = i, k = 0; (string[j] == substring[k] && (j < strlen(string))); j++,k++) {
            if (! substring[k + 1]) {
                count++;
            }
        }
    }
    return count;
}
//第二个函数：计算一个子串在字符串中的位置
int  substring_index( const   char   * s1, const   char   * s2,  int  pos) {
    int i,j,k;
    for( i = pos ; s1[i] ; i++ ) {
        for( j = i, k = 0 ; s1[j] == s2[k]; j++,k++ ){
            if (! s2[k + 1]) {
                return i;
            }
        }
    }
    return -1;
}
//第三个函数：读取已经打开的一个CSV文件的一行，将这一行处理到一个数组中。
char  * fgetcsvline(vector < string >   & csv_databuf, FILE  * fhead)  {
    char  *ret_stat;
    char  data_buf[1024];
    string stringbuf;
    ret_stat = fgets( data_buf, 1024, fhead );

    if (ret_stat != NULL) {
        int len = strstr_cnt(data_buf,"\",\"");
        if (len > 0){
            int pos = substring_index(data_buf,"\",\"",0);
            int startpos = 1;
            string csv_buf;
            while (pos > 0) {
                stringbuf = (string)data_buf;
                csv_buf = stringbuf.substr(startpos,pos - startpos);
                csv_databuf.push_back(csv_buf);
                startpos = pos + 3;
                pos = substring_index(data_buf,"\",\"",pos + 2);
            }
            if ((substring_index(data_buf,"\n",0)) > 0){
                csv_buf = stringbuf.substr(startpos, stringbuf.length() - startpos - 2);
            } else {
                csv_buf = stringbuf.substr(startpos, stringbuf.length() - startpos - 1);
            }
            csv_databuf.push_back(csv_buf);
        }
    }

    return ret_stat;
}
//int  main()  {
//    FILE  *fp_head;
//    char* csvFileName = "../Data.CSV";
//    char  *ret_stat;
//    vector<string> csv_data;
//
//    fp_head = fopen( csvFileName, "rt" );
//    ret_stat = fgetcsvline(csv_data, fp_head);
//    while (ret_stat != NULL) {
//        //get csv data use csv_data[n]
//        ret_stat = fgetcsvline(csv_data, fp_head);
//        cout <<ret_stat;
//    }
//
//    return 0;
//}